package edu.csu.smartpark.shiro;

import edu.csu.smartpark.dao.UserDAO;
import edu.csu.smartpark.model.PO.UserPO;
import edu.csu.smartpark.util.JwtUtil;
import edu.csu.smartpark.util.StringUtil;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/*
* @Description: 负责校验jwt token的realm
* @Author: LZY
* @Date: 2021/4/19 22:05
*/
@Component
public class JwtRealm extends AuthorizingRealm {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserDAO userDAO;

    @Override
    public boolean supports(AuthenticationToken token) {
        //这个token就是从过滤器中传入的jwtToken
        return token instanceof JwtToken;
    }

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //认证
        //这个token就是从过滤器中传入的jwtToken
        // 判定此token是否为有效token,无效这校验不通过
        String jwt = (String) token.getPrincipal();
        if (StringUtil.isEmpty(jwt)){
            throw new IncorrectCredentialsException("Authorization token is invalid");
        }
        Claims claims = jwtUtil.decode(jwt);
        String userId = (String)claims.get("userId");
        Map<Object, Object> authorization = jwtUtil.getTokenFromCache(userId);
        if (authorization == null || authorization.get("token") == null || !jwt.equals(authorization.get("token"))){
            throw new IncorrectCredentialsException("Authorization token is invalid");
        }
        if (!jwtUtil.isVerify(jwt)) {
            throw new IncorrectCredentialsException("Authorization token is invalid");
        }
        return new SimpleAuthenticationInfo(jwt, jwt, "JwtRealm");
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String jwt = (String) principals.getPrimaryPrincipal();
        String userId = (String) jwtUtil.decode(jwt).get("userId");
        // 从数据库用户角色信息加载
        UserPO userPO = userDAO.selectById(userId);
        List<String> roles = StringUtil.splits(userPO.getRoles(), ",");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addRoles(roles);
        return authorizationInfo;
    }
}

